﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization;
using System.Net;
using System.Web.Script.Serialization;

namespace Translator
{
	namespace Integration.Google
	{
		/// Defines a response from one of Google's AJAX APIs.
		/// The type of object, being returned.
		[DataContract]
		public class GoogleAjaxResponse<T>
		{
			/// Gets or sets the response data.
			/// The responseData from Google AJAX API Call. The response data.
			[DataMember(Name = "responseData", Order = 0)]
			public T ResponseData { get; set; }
		}

		/// Defines a response from the Google AJAX Translate API.
		[DataContract]
		public class TranslationResponse
		{
			/// Initializes a new instance of the  class.
			public TranslationResponse()
			{
				this.ResponseStatus = HttpStatusCode.OK;
			}

			/// Gets or sets the translated text.
			/// The translated text.
			[DataMember(Name = "translatedText", Order = 0)]
			public string TranslatedText { get; set; }

			/// Gets or sets the response details.
			/// The response details.
			[DataMember(Name = "responseDetails", Order = 1)]
			public object ResponseDetails { get; set; }

			/// Gets or sets the response status.
			/// The response status.
			[DataMember(Name = "responseStatus", Order = 2)]
			public HttpStatusCode ResponseStatus { get; set; }
		}


		/// An API Client for the Google AJAX Translate API.
		public class TranslateApi
		{
			/// The JavaScript serializer
			private JavaScriptSerializer _Serializer = new JavaScriptSerializer();

			/// Translates the text.
			public string TranslateText(string inputText, string sourceLanguage, string destinationLanguage, string referrer, string apiKey)
			{
				string requestUrl = string.Format("http://ajax.googleapis.com/ajax/services/language/translate?v=1.0&q={0}&langpair={1}|{2}&key={3}",
					System.Web.HttpUtility.UrlEncode(inputText), sourceLanguage.ToLowerInvariant(), destinationLanguage.ToLowerInvariant(), apiKey);

				try
				{
					HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(requestUrl);
					using (HttpWebResponse resp = (HttpWebResponse)request.GetResponse())
					{
						using (System.IO.StreamReader sr = new System.IO.StreamReader(resp.GetResponseStream()))
						{
							string responseJson = sr.ReadToEnd();

							GoogleAjaxResponse<TranslationResponse> translation = this._Serializer.Deserialize<GoogleAjaxResponse<TranslationResponse>>(responseJson);

							if (translation != null && translation.ResponseData != null && translation.ResponseData.ResponseStatus == HttpStatusCode.OK)
							{
								return translation.ResponseData.TranslatedText;
							}
							else
							{
								return String.Empty;
							}
						}
					}
				}
				catch (Exception)
				{
					return String.Empty;
				}
			}

		}

	}
}
